<template>
  <div class="sidebar-main">
    <div class="function-list">
      <div
        class="function-list-item"
        v-for="(item, index) in functionList"
        :key="index"
        @click="funcItem(item.path, index)"
        :class="{ selected: selectedIndex === index }"
      >
        <img :src="getItemImage(index)" alt="" />
        <p>{{ item.name }}</p>
        <div v-if="index > 1" class="close-button" @click.stop="closeApp(index)">×</div>
      </div>
    </div>
    <!-- 固定在底部的系统设置按钮 -->
    <div
      class="settings-button"
      @mouseover="settingsHover = true"
      @mouseleave="settingsHover = false"
      @click="funcItem('/setting', -1)"
    >
      <img :src="getSettingsImage()" alt="" />
    </div>
  </div>
</template>

<script>
import { ElMessageBox } from 'element-plus'
import emitter from '../../utils/eventBus'

export default {
  data() {
    return {
      avatarUrl: '',
      username: 'typs****@163.com',
      selectedIndex: 0, // 当前选中的索引，默认选中第一个
      settingsHover: false,
      functionList: [
        {
          name: '我的应用',
          selectedImg: new URL('@/assets/sidebar/home-selected.png', import.meta.url).href,
          defaultImg: new URL('@/assets/sidebar/home-default.png', import.meta.url).href,
          path: '/desktop'
        },
        {
          name: '应用商店',
          selectedImg: new URL('@/assets/sidebar/czhi-selected.svg', import.meta.url).href,
          defaultImg: new URL('@/assets/sidebar/czhi-default.svg', import.meta.url).href,
          path: '/appStore'
        }
      ]
    }
  },
  created() {
    // 监听事件总线上的update-opened-apps事件
    emitter.on('update-opened-apps', this.updateOpenedApps)
  },
  beforeUnmount() {
    // 清理事件监听
    emitter.off('update-opened-apps', this.updateOpenedApps)
  },
  methods: {
    closeApp(index) {
      // 从functionList中移除应用
      this.functionList.splice(index, 1)
      // 如果关闭的是当前选中的应用，则切换到上一个应用
      if (index === this.selectedIndex) {
        const prevIndex = index - 1
        this.selectedIndex = prevIndex
        const prevItem = this.functionList[prevIndex]
        if (prevItem.path === '/dynamicApp') {
          this.$router.push({
            path: prevItem.path,
            query: {
              appType: prevItem.appType,
              appData: btoa(encodeURIComponent(JSON.stringify(prevItem.appData)))
            }
          })
        } else {
          this.$router.push(prevItem.path)
        }
      } else if (index < this.selectedIndex) {
        // 如果关闭的应用在当前选中应用之前，需要更新selectedIndex
        this.selectedIndex--
      }
    },
    updateOpenedApps(app) {
      // 检查应用是否已经在列表中
      const existingAppIndex = this.functionList.findIndex((item) => item.name === app.appName)
      if (existingAppIndex === -1) {
        // 如果应用不在列表中，添加到functionList
        this.functionList.push({
          name: app.appName,
          selectedImg: app.appIconImg,
          defaultImg: app.appIconImg,
          path: '/dynamicApp',
          appType: app.appType,
          appData: app.appData
        })
        this.selectedIndex = this.functionList.length - 1
      } else {
        // 如果应用已经在列表中，更新selectedIndex
        this.selectedIndex = existingAppIndex
      }
    },
    funcItem(path, index) {
      this.selectedIndex = index
      if (path === '/login') {
        // 其他清除token的操作
        ElMessageBox.confirm('确认需要退出吗?', '退出提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } else if (path === '/dynamicApp') {
        const item = this.functionList[index]
        this.$router.push({
          path,
          query: {
            appType: item.appType,
            appData: btoa(encodeURIComponent(JSON.stringify(item.appData)))
          }
        })
      } else {
        this.$router.push(path)
      }
    },
    getItemImage(index) {
      return this.functionList[index].selectedImg
    },
    getSettingsImage() {
      return this.settingsHover
        ? new URL('@/assets/sidebar/set-selected.svg', import.meta.url).href
        : new URL('@/assets/sidebar/set-default.svg', import.meta.url).href
    }
  }
}
</script>

<style scoped>
@import './index.css';
</style>
